package com.example.thread.d9CompletableFuture2.d4异步任务编排;

import com.example.thread.d9CompletableFuture2.CommonUtils;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

// CompletableFuture<R> thenCompose(Function<T,CompletableFuture<R>> func)
public class d1_ThenComposeDemo {

    public static CompletableFuture<String> readFileFuture(String str) {
        return CompletableFuture.supplyAsync(()-> {
            String s = CommonUtils.readFile("hello,world");
            return s;
        });
    }

    public static CompletableFuture<String[]> splitFuture(String content) {
        return CompletableFuture.supplyAsync(()-> {
            String[] filterWorlds = content.split(",");
            return filterWorlds;
        });
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

//        CompletableFuture<CompletableFuture<String[]>> future = readFileFuture("文件").thenApply(content -> {
//            return splitFuture(content);
//        });

        CompletableFuture<String[]> future = readFileFuture("hello").thenCompose(content -> {
            return splitFuture(content);
        });

        String[] strs = future.get();
        CommonUtils.printThreadLog("strs:"+ Arrays.toString(strs));

        /**
         * thenApply(function<T,R>)
         * 重心在于对上一步异步任务的结果T进行应用转换，经function回调转换后的结果R是一个简单的值
         *
         * thenCompose(Funtion<T,CompletableFutute<R>>)
         * 重心在于对上一步异步任务的结果T进行应用，经Function回调转换后的结果是一个CompletableFutute对象
         * 结论：
         *  编排两个依赖关系的异步任务（CompletableFutute对象），请使用thenCompose()方法
         */

    }
}
